package com.lnsf.bookstore.system.admin.controller;

import javax.servlet.http.HttpServletRequest;

import com.github.pagehelper.PageInfo;
import com.lnsf.bookstore.common.annotation.SysLog;
import com.lnsf.bookstore.common.dto.ResultFailDto;
import com.lnsf.bookstore.common.dto.ResultSuccessDto;
import com.lnsf.bookstore.common.session.SessionProvider;
import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import com.lnsf.bookstore.system.user.service.UserService;
import com.lnsf.bookstore.system.user.vo.User;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/sysuser")
public class AdminController {

	@Autowired
	private UserService userService;

	@Autowired
	private SessionProvider sessionProvider;

	@RequestMapping("/v_list.do")
	public String v_list(){
		return "admin/sysuser/user";
	}


	@RequestMapping("/info/{userId}")
	@ResponseBody
	public Object info(ModelMap modelMap, HttpServletRequest request, @PathVariable("userId") Integer userId){
	/*	VipUser vipuser = sessionProvider.getUser();*/
		Map<String,Object> map = new HashMap<String, Object>();
		User user = userService.selectById(userId);
		map.put("user",user);
		return  map;
	}

	/**
	 * 查看所有列表
	 */
	@SysLog("查看管理员列表")
	@RequestMapping("/queryAll")
	@ResponseBody
	public Object queryAll(@RequestParam Map<String, Object> params, User user) {
		PageInfo<User> pageInfo = userService.selectAllAdmin(params,user);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("page",pageInfo);
		return map;
	}

	/**
	 * 修改、新增操作
	 */
	@SysLog("修改，新增管理员")
	@RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
	@ResponseBody
	public Object saveOrUpdate(HttpServletRequest request, Integer id , @RequestBody  User user, ModelMap modelMap){
		if(user.getId()==null){//新增
			//verifyForm(permission);
			this.salt(user);//加盐加密
			userService.saveUser(user);
			//rolePermissionService.saveOrUpdate(role);
		}else{//修改
			//verifyForm(permission);
			userService.updateUser(user);
			//rolePermissionService.saveOrUpdate(role);
		}
		return new ResultSuccessDto("操作成功");
	}

	/**
	 * 删除用户
	 */
	@SysLog("删除用户")
	@RequestMapping("/delete")
	@ResponseBody
	//@RequiresPermissions("sys:user:delete")
	public Object delete(@RequestBody Integer[] ids) {
		if (ArrayUtils.contains(ids, 10)) {
			return new ResultFailDto("系统管理员不能删除");
		}

		if (ArrayUtils.contains(ids, sessionProvider.getUser().getId())) {
			return new ResultFailDto("当前用户不能删除");
		}

		userService.deleteBatch(ids);

		return new ResultSuccessDto("操作成功");
	}

	/**
	 * 修改登录用户密码
	 * @param password
	 * @param newPassword
	 * @return
	 */
	@SysLog("修改密码")
	@RequestMapping("/password")
	public Object alertPassword(String password, String newPassword){
		//String salt = UUID.randomUUID().toString().replaceAll("-", "");//盐
		int hashIterations = 15;//迭代次数
		//vipuser.setSalt(salt);
		User user = sessionProvider.getUser();
		//新密码加密
		SimpleHash simpleHash_new = new SimpleHash("md5",newPassword, user.getSalt(), hashIterations);
		//旧密码加密
		SimpleHash simpleHash = new SimpleHash("md5", user.getPassword(), user.getSalt(), hashIterations);
		int count = userService.updatePassword(user.getId(),simpleHash.toString(),simpleHash_new.toString());
		if(count==0){
			return  new ResultFailDto("原密码不正确");
		}
		sessionProvider.logout();
		return new ResultSuccessDto();

	}

	/**
	 * PUT 启用/冻结管理员
	 * @return
	 */
	/*@ApiOperation(value = "启用/冻结管理员", notes = "根据url管理员ID启动/冻结管理员")
	@RequiresPermissions("administrator:list:audit")*/
	@RequestMapping(value = "/audit/{userId}")
	@ResponseBody
	public Object audit(@PathVariable("userId") Long userId) {
		/*AuthorizingUser authorizingUser = SingletonLoginUtils.getUser();
		if (authorizingUser != null) {
			Integer count = userService.updateStatus(userId);
			return new CmsResult(CommonReturnCode.SUCCESS, count);
		} else {
			return new CmsResult(CommonReturnCode.UNAUTHORIZED);
		}*/
		return  null;
	}

	/**
	 * 初始密码是123456
	 * @param user
	 */
	private void salt(User user){
		String salt = UUID.randomUUID().toString().replaceAll("-", "");//盐
		int hashIterations = 15;//迭代次数
		System.out.println(salt);
		user.setSalt(salt);
		SimpleHash simpleHash = new SimpleHash("md5", "123456", salt, hashIterations);
		user.setPassword(simpleHash.toString());
	}





	
	
	
	
	
	
	
}
